/**
 * Filename: NativeAlbumFragment.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/10 1:11
 */
package com.github.postsanf.yinian.fragment;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopListImageDir;
import com.github.postsanf.yinian.adapter.LocalStickyImportGridAdapter;
import com.github.postsanf.yinian.bean.YNFileInfo;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.nativestick.StickyGridHeadersGridView;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.YNNativeComparator;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

/**
 * 本地图库
 */
public class LocalAlbumImportFragment extends BaseFragment implements View.OnClickListener, PopListImageDir.OnImageDirSelected, ISkinUpdate {
    private View view;                           // 上下文视图
    private ProgressDialog mProgressDialog;
    private TextView btn_native_up_choose;
    private StickyGridHeadersGridView mNative_grid_view;
    private Map<String, Integer> sectionMap = new HashMap<>();
    private List<YNNativeImage> mNativeImageList = new ArrayList<>();
    private static int section = 1;
    private boolean isChoose = false;
    private LocalStickyImportGridAdapter mAdapter;
    private PopListImageDir mListImageDirPopupWindow;
    private int mScreenHeight;                    // 屏高
    private RelativeLayout rl_native_up_bottom;
    // 所有的图片文件夹
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private ImageView iv_btn_dir_choose;
    private HashSet<String> mDirPaths = new HashSet<String>();
    private int totalCount;
    private int mPicsSize;                        // 文件夹图片数量
    private File mImgDir;                        // 图片数量最多的文件夹
    private List<String> mImgs;                            // 所有的图片
    private Resources mResource;

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mProgressDialog.dismiss();
            // 为View绑定数据
            data2View();
            // 初始化展示文件夹的popupWindw
            initListDirPopupWindw();
        }
    };

    // 数据绑定
    private void data2View() {
        if (mImgDir == null) {
            Toast.makeText(getActivity(), "图片没扫描到", Toast.LENGTH_SHORT).show();
            return;
        }
        File[] files = mImgDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String filename = file.getName().toLowerCase();
                if (file.length() > 0 && !filename.contains(".9")) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                }
                return false;
            }
        });
        mNativeImageList.clear();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String imgPath = file.getPath();
            long imgTime = file.lastModified();
            Date currentTime = new Date(imgTime);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            YNNativeImage mNativeItem = new YNNativeImage(imgPath, dateString);
            mNativeImageList.add(mNativeItem);
        }
        Collections.sort(mNativeImageList, new YNNativeComparator());
        for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
            YNNativeImage mNativeItem = it.next();
            String ym = mNativeItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mNativeItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mNativeItem.setSection(sectionMap.get(ym));
            }
        }
        mAdapter = new LocalStickyImportGridAdapter(getActivity(), mNativeImageList, true, mNative_grid_view);
        if (mResource != null) {
            mAdapter.setResource(mResource);
        }
        mNative_grid_view.setAdapter(mAdapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        BaseApplication.getInstance().mActivitys.add(this);
        mScreenHeight = DisplayUtils.getScreenHeightPixels(getActivity());
        initListDirPopupWindw();
        initView();
        initEvent();
        return view;
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_fragment_native_album, null);
        mNative_grid_view = (StickyGridHeadersGridView) view.findViewById(R.id.native_grid_view);
        rl_native_up_bottom = (RelativeLayout) view.findViewById(R.id.rl_native_up_bottom);
        btn_native_up_choose = (TextView) view.findViewById(R.id.btn_native_up_choose);
        iv_btn_dir_choose = ((ImageView) view.findViewById(R.id.iv_btn_dir_choose));
        btn_native_up_choose.setOnClickListener(this);
        //设置头部跟随滑动
        mNative_grid_view.setAreHeadersSticky(false);
        getImages();
    }

    private void initEvent() {
        // 相册列表触发
        btn_native_up_choose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_btn_dir_choose.setImageResource(R.drawable.up_expend);
                mListImageDirPopupWindow.showAsDropDown(rl_native_up_bottom, 0, 0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = .9f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 选择发布
            case R.id.btn_native_up_choose:
                // 显示选择相册弹框
                mListImageDirPopupWindow.showAtLocation(mNative_grid_view, Gravity.BOTTOM, 0, 0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = .8f;
                getActivity().getWindow().setAttributes(lp);
                mAdapter.setSelectStatus(true);
                mAdapter.notifyDataSetChanged();
                break;
        }
    }

    // 初始化展示文件夹的popupWindw
    private void initListDirPopupWindw() {
        mListImageDirPopupWindow = new PopListImageDir(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFloders, LayoutInflater.from(getContext().getApplicationContext())
                .inflate(R.layout.yn_album_list_dir, null));
        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv_btn_dir_choose.setImageResource(R.drawable.up_expend);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1.0f;
                getActivity().getWindow().setAttributes(lp);
            }
        });
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getActivity(), "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(getContext(), "", CommonConstants.TIP_LOAD_DATA);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = getActivity().getContentResolver();
                Cursor mCursor = mContentResolver.query(mImageUri, null, null, null, MediaStore.Images.Media.DATE_ADDED);
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));
                    long times = mCursor.getLong(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATE_ADDED));

                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;

                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;

                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".gif") || filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });

                    int picSize = (pics != null) ? pics.length : 0;
                    totalCount += picSize;

                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;
                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    @Override
    public void selected(YNImageFloder floder) {
        mImgDir = new File(floder.getDir());
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        File[] files = mImgDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String filename = file.getName().toLowerCase();
                if (file.length() > 0 && !filename.contains(".9")) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                }
                return false;
            }
        });
        mNativeImageList.clear();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String imgPath = file.getPath();
            long imgTime = file.lastModified();
            Date currentTime = new Date(imgTime);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(currentTime);
            YNNativeImage mNativeItem = new YNNativeImage(imgPath, dateString);
            mNativeImageList.add(mNativeItem);
        }
        Collections.sort(mNativeImageList, new YNNativeComparator());
        for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
            YNNativeImage mNativeItem = it.next();
            String ym = mNativeItem.getTime();
            if (!sectionMap.containsKey(ym)) {
                mNativeItem.setSection(section);
                sectionMap.put(ym, section);
                section++;
            } else {
                mNativeItem.setSection(sectionMap.get(ym));
            }
        }
        mAdapter = new LocalStickyImportGridAdapter(getActivity(), mNativeImageList, true, mNative_grid_view);
        mNative_grid_view.setAdapter(mAdapter);

        mAdapter.notifyDataSetChanged();
        btn_native_up_choose.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mProgressDialog.dismiss();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    @Override
    public void updateTheme() {
        try {
            Resources mResource = SkinPackageManager.getInstance(getActivity()).mResources;
            btn_native_up_choose.setTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
            rl_native_up_bottom.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
            mAdapter.setResource(mResource);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(getActivity()).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }
}